package com.yc.weixin.web.Handler;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yc.utils.YcUtils;
import com.yc.weixin.entity.Major;
import com.yc.weixin.entity.WeiXinUserRealInfo;
import com.yc.weixin.manager.MenuManager;
import com.yc.weixin.service.CoreService;
import com.yc.weixin.util.MenuUtil;
import com.yc.weixin.util.SignUtil;
import com.yc.weixin.util.WeiXinCommonUtil;
import com.yc.weixin.util.WeixinbasicKey;

/**
 * 微信请求处理的核心类
 * @author shuang
 *
 */
@Controller
@RequestMapping("/weixin")
public class AutographHandler{
	
	@Resource(name="coreService")
	private CoreService coreService;

	@PostConstruct
	public void init(){
		//自动创建图片基础文件夹
		String uploadPath="../uploadPic";
		//应该判断该路径是否存在，如果不存在则就创建一个
		File file=new File(uploadPath);
		//如果目录不存在，则创建
		if(!file.exists()){
			file.mkdirs();
		}
		//定时获取AccessToken，两小时内有效，每天最多获取2000次
		Thread t= new Thread(new Runnable() {
				public void run() {
					while (true) {
						WeixinbasicKey.ACCESSTOKEN=WeiXinCommonUtil.getToken(WeixinbasicKey.APPID, WeixinbasicKey.APPSECRET).getAccessToken();
						try {
							Thread.sleep(700000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		t.start();
	}

	/**
	 *
	 * @param signature/微信加密签名
	 * @param timestamp时间搓
	 * @param nonce随机数
	 * @param echostr随机字符串
	 * @return
	 */
	
	@RequestMapping(value={"/weixinservice.do"},method=RequestMethod.GET)
	@ResponseBody
	public String AutographGetMethod(String signature,String timestamp,String nonce,String echostr){
		System.out.println("微信签名认证中");
		try {	
			if(   SignUtil.checkSignature(signature, timestamp, nonce)){	
				//签名认证成功后自动创建菜单，然后再返回随机数，创建菜单有一个接口
				try {
					//MenuUtil.createMenu(MenuManager.getMenu(), WeiXinCommonUtil.getToken(WeixinbasicKey.APPID, WeixinbasicKey.APPSECRET).getAccessToken());
					MenuUtil.createMenu(MenuManager.getMenu(), WeixinbasicKey.ACCESSTOKEN);
					return echostr;
				} catch (Exception e) {
					YcUtils.logger.error(e.getMessage());
					e.printStackTrace();
					return e.getMessage();
				}
			}
		} catch (NoSuchAlgorithmException e) {
			YcUtils.logger.error(e.getMessage());
		}
		return null;	
	}
	
	@RequestMapping(value={"/weixinservice.do"},method=RequestMethod.POST)
	@ResponseBody
	public String AutoGraphPostMethod(HttpServletRequest request,String signature,String timestamp,String nonce,String echostr){
	try {
			YcUtils.logger.debug(    signature+"  "+timestamp+"  "+nonce);
			if(   SignUtil.checkSignature(signature, timestamp, nonce)){//请求校验
			
				String respXml=coreService.processRequest(request);//请求处理
				YcUtils.logger.debug(respXml);
				return respXml;//响应消息
			}
		} catch (NoSuchAlgorithmException e) {
			YcUtils.logger.error(e.getMessage());
			return  e.getMessage();
		}
		return null;	
	
	}
	/**
	 * 处理用户授权网页跳转
	 * @param code
	 * @return
	 */
	@RequestMapping(value={"/userCode.do"})
	public String userCode(String code,Model model){
		try {
			JSONObject js = WeiXinCommonUtil.httpsRequest(WeixinbasicKey.GETACCESS_TOKENBYCODE.replace("APPID", WeixinbasicKey.APPID).replace("SECRET", WeixinbasicKey.APPSECRET).replace("CODE", code), "POST", null);
			model.addAttribute("openid", js.getString("openid"));
			List<Major>majors=coreService.selectAllMajor();
			model.addAttribute("majors", majors);
		} catch (Exception e) {
			YcUtils.logger.error(e.getMessage());
			e.printStackTrace();
		}
		return "forward:/weixin/front/zxbm.jsp";
	}
	
	@RequestMapping(value={"/onLineRegister.do"})
	@ResponseBody
	public boolean onLineRegister(WeiXinUserRealInfo weiXinUserRealInfo){
		if(weiXinUserRealInfo.getMajor()==null||weiXinUserRealInfo.getName()==null
				||weiXinUserRealInfo.getOpenid()==null||weiXinUserRealInfo.getSchool()==null
				||weiXinUserRealInfo.getTelphone()==null){
			return false;
		}
		int result=coreService.updateUserRealInfo(weiXinUserRealInfo);
		if(result>0){
			return true;
		}
		return false;
	}
	
}
